package bitmap;

import java.util.HashMap;
import java.util.Set;

public class BMPText
{
	HashMap<String, int[][]> font;

	public BMPText()
	{
		lodFont();
	}

	private void lodFont()
	{
		FontReader fr = new FontReader("C:/tmp/font01.font");
		fr.process();
		font = fr.getFont();

	}

	public int[][] print(String txt, int[][] bmp)
	{
		return print(txt, bmp, BMPSave.WHITE, 1);
	}

	public int[][] print(String txt, int[][] bmp, int color, int scale)
	{
		// Set<String> letters = font.keySet();
		// for(String l : letters)
		// System.out.println("{"+l+"}");

		HashMap<String, int[][]> fontToUse = font;

		if (scale > 1)
		{
			fontToUse = scaleFont(scale);
		}

		int offsetCol = 0;
		int offsetRow = 0;
		int maxRows = bmp.length;
		int maxCols = bmp[0].length;

		int riga = maxRows - 2;
		int colonna = 1;
		for (int i = 0; i < txt.length(); i++)
		{

			String s = txt.substring(i, i + 1);
			//System.out.println(s);
			// gestisce scape
			if (s.equalsIgnoreCase("\n"))
			{
				offsetCol = 0;
				offsetRow = offsetRow + 7;
				continue;
			}
			// System.out.println("<"+s+">");
			int[][] map;
			if (fontToUse.get(s) == null)
				map = fontToUse.get("null");
			else
				map = fontToUse.get(s);

			int rowLetter=map.length;
			int colLetter=map[0].length;
			for (int r = 0; r < rowLetter; r++)
			{
				for (int c = 0; c < colLetter; c++)
				{
					if (map[r][c] == 1)
					{
						int row = riga - r - offsetRow;
						int col = colonna + c + offsetCol;

						// gestisce a capo
						if (col + colLetter+2 > maxCols)
						{
							offsetCol = 0;
							offsetRow = offsetRow + rowLetter+2;
						}

						row = riga - r - offsetRow;
						col = colonna + c + offsetCol;

						if (row > 0 && col > 0 && row < maxRows && col < maxCols)
						{

							bmp[row][col] = color;
						}
					}

				}
			}
			offsetCol = offsetCol +colLetter+2;
		}

		return bmp;
	}

	private HashMap<String, int[][]> scaleFont(int scale)
	{
		HashMap<String, int[][]> res = new HashMap<String, int[][]>();
		Set<String> letters = font.keySet();
		for (String key : letters)
		{
			int[][] map = font.get(key);
			int newRows=map.length * scale;
			int newCols=map[0].length * scale;
			int[][] newMap = new int[newRows][newCols];
			
			for (int r = 0; r < newRows; r++)
			{
				for (int c = 0; c < newCols; c++)
				{
					int rOrr=r/scale;
					int cOrr=c/scale;					
					newMap[r][c]=map[rOrr][cOrr];
					
				}
			}
			
			res.put(key, newMap);

		}

		return res;
	}
}
